package com.levi.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shentong
 * @since 2022/6/5 7:00 PM
 * 自定义Sentinel返回结果，根据不同的异常返回不同的类型
 */
@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        String result = "";
        if (e instanceof FlowException) {
            result = "你被限流了";
        } else if (e instanceof DegradeException) {
            result = "你被降级了";
        }else if (e instanceof ParamFlowException){
            result = "参数限流";
        }else if (e instanceof SystemBlockException){
            result = "系统异常";
        }else if (e instanceof AuthorityException){
            result = "权限不够";
        }
        response.getWriter().write(result);
    }

}
